package com.skillworld.webapp.web.pages.rest.item;

import org.apache.tapestry5.annotations.ContentType;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;

import com.skillworld.webapp.model.itemservice.BagFullException;
import com.skillworld.webapp.model.itemservice.ItemService;
import com.skillworld.webapp.model.util.InvalidArgumentException;
import com.skillworld.webapp.web.util.ErrorMessages;
import com.skillworld.webapp.web.util.UserSession;

import es.udc.pojo.modelutil.exceptions.InstanceNotFoundException;

@ContentType("text/xml")
public class GiftItem
{
    @SuppressWarnings("unused")
    @Property
    private String errorMessage = null;

    @Inject
    private ItemService itemService;

    @SessionState(create=false)
    private UserSession userSession;
   
    private boolean userSessionExists;

    @Inject
    private Request request;
   

    void onPassivate() 
    {
        return;
    }
    
    void onActivate()
    {
        if (!userSessionExists)
        {
            errorMessage = ErrorMessages.NOT_LOGGED_IN;
            return;
        }
        
        String entryParam = request.getParameter("entry");
        String recipientParam = request.getParameter("recipient");
                
        if (entryParam == null || recipientParam == null)
        { 
            errorMessage = ErrorMessages.INVALID_ARGUMENTS;
            return;
        }
        
        try 
        {
            long recipientId = Long.parseLong(recipientParam);
            long entryId = Long.parseLong(entryParam);
            itemService.giftItem(userSession.getUserId(), 
                                    recipientId, entryId);
        }
        catch (NumberFormatException e)
        { errorMessage = ErrorMessages.INVALID_ARGUMENTS; }
        catch (InvalidArgumentException e) 
        { errorMessage = ErrorMessages.INVALID_ARGUMENTS; }
        catch (InstanceNotFoundException e)
        { errorMessage = ErrorMessages.INSTANCE_NOT_FOUND; }
        catch (BagFullException e)
        { errorMessage = ErrorMessages.BAG_IS_FULL; } 
    } 
}
